﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace FileManager
{
    /*  struct
     *      ConfigInfo
     *          DeviceArea  区域名称
     *          DeviceName	设备名称
     *          DeviceIP	设备IP
     *          DevicePort	设备端口，通常为8000
     *          DeviceUser	设备用户名
     *          DevicePass	设备密码
     *          DeviceChannel	设备通道，从1开始计数
     *          DeviceStream		设备码流，0为主码流，1为副码流
     *          Protocol		设备协议，TCP、UDP或RTP  
     *  path
     *      DefaultConfig = .\config\
     *      DefaultRecord = .\record\
     *      DefaultSnap = .\snap\
     *      DefaultAlarm = .\Alarm\
     *      DefaultMap = .\Map\
     *      DefaultStyle = .\Style\
     *      
     *  config
     *      Dictionary<string, Dictionary<string, ConfigInfo>> GetDeviceConfig();

     *      Dictionary<string, List<string>> GetDeviceList();   //[DeviceArea  DeviceName]
     *  record
     *      string GetRecordFullPath(string DeviceArea,string DeviceName);
     *      List<string> GetRecordDay(string DeviceArea,string DeviceName, string year, string month);
     *      FileInfo[] GetRecordList(string DeviceArea,string DeviceName, string year, string month, string day);
     *      
     *      
     */
    public class DeviceInfo
    {
        public string DeviceIp {get;private set;}
        public string DevicePort {get;private set;}
        public string DeviceUser { get; private set; }
        public string DevicePass { get; private set; }
        public byte DeviceAddress { get; private set; }

        public DeviceInfo(string ip, string port, string user, string pass, byte address)
        {
            this.DeviceIp = ip;
            this.DevicePort = port;
            this.DeviceUser = user;
            this.DevicePass = pass;
            this.DeviceAddress = address;
        }

    }

    public class ConfigInfo
    {
        Dictionary<string, string> Configs = new Dictionary<string, string>();

        public ConfigInfo(string fullPath)
        {
            string config = null;
            FileStream fs = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.None);
            StreamReader sr = new StreamReader(fs, System.Text.Encoding.GetEncoding("GB2312"));
            sr.BaseStream.Seek(0, SeekOrigin.Begin);
            //string strLine = sr.ReadLine();
            //while (strLine != null)
            //{

            //    if (!ProcessString(strLine, config))
            //        return false;
            //    strLine = sr.ReadLine();
            //}
            config = sr.ReadLine();
            while (config != null)
            {
                
                config = RegexProcess.RepalceSpace(config);
                string[] keyvalue = config.Split('=');
                if (keyvalue.Length == 2) Configs.Add(keyvalue[0], keyvalue[1]);
                config = sr.ReadLine();
            } 
            sr.Close();
            fs.Close();
        }

        public string GetValue(string key)
        {
            if (Configs.ContainsKey(key)) return Configs[key];
            else return string.Empty;
        }
    }
    
    public class FileConfig
    {
        private string DefaultConfigPath = @".\config\";
        private string DefaultRecordPath = @".\record\";
        private string DefaultSnapPath = @".\snap\";
        private string DefaultAlarmPath = @".\Alarm\";
        private string DefaultMapPath = @".\Map\";
        private string DefaultStylePath = @".\Style\";
        public Dictionary<string, Dictionary<string, ConfigInfo>> Dics = new Dictionary<string, Dictionary<string, ConfigInfo>>();

        //private string FilePath = null;
        public FileConfig()
        {
        }
        /// <summary>
        /// 从给定目录下面读出所有的配置文件
        /// </summary>
       /// <returns></returns>
        public bool ReadAllConf()
        {
            DirectoryInfo Dir = new DirectoryInfo(@"./conf");
            FileInfo[] Files = Dir.GetFiles();
            for (int i = 0; i < Files.Length; i++)
            {
                if (!ReadConf(Files[i].FullName))
                    return false;
            }
            return true;
        }

        /// <summary>
        /// 读一个具体的配置文件，将配置文件中的内容放到字典中去
        /// </summary>
        /// <param name="ConfFile">配置文件的名字</param>
        /// <returns></returns>
        public bool ReadConf(string ConfFile)
        {
            try
            {
                Dictionary<string, ConfigInfo> Dic = new Dictionary<string, ConfigInfo>();
                ConfigInfo config = new ConfigInfo(ConfFile);

                Dic[config.GetValue("DeviceName")] = config;
                if (!Dics.ContainsKey(config.GetValue("DeviceArea")))
                    Dics.Add(config.GetValue("DeviceArea"), Dic);
                else
                {
                    Dics[config.GetValue("DeviceArea")].Add(config.GetValue("DeviceName"), config);
                }
            }
            catch
            {
                
            }
            
            return true;
        }

        /// <summary>
        /// 解析配置文件的每一行，看是否合法
        /// </summary>
        /// <param name="StrLine"></param>
        /// <param name="Dic"></param>
        /// <returns></returns>
        private bool ProcessString(string StrLine, Dictionary<string, string> Dic)
        {

            string Str = RegexProcess.RepalceSpace(StrLine);
            string[] SpiltStr = Str.Split(new char[] { '=' });
            if (SpiltStr.Length != 2)
            {
                throw new CustomException("不合法的配置文件");
              
            }
            if (Dic.ContainsKey(SpiltStr[0])) Dic[SpiltStr[0]] = SpiltStr[1];

           
            return true;
        }

        /// <summary>
        /// 根据区域名，设备名获得录像的根目录
        /// </summary>
        /// <param name="DeviceArea">区域名</param>
        /// <param name="DeviceName">设备名</param>
        /// <returns></returns>
        public string GetRecordRoot(string DeviceArea,string DeviceName)
        {
             return Dics[DeviceArea][DeviceName].GetValue("RecordPath")+DeviceArea + "\\" + DeviceName + "\\";
        }
        public string GetAlarmRoot(string DeviceArea, string DeviceName)
        {
            return Dics[DeviceArea][DeviceName].GetValue("AlarmPath") + DeviceArea + "\\" + DeviceName + "\\";
        }
        public string GetSnapRoot(string DeviceArea, string DeviceName)
        {
            return Dics[DeviceArea][DeviceName].GetValue("SnapPath") + DeviceArea + "\\" + DeviceName + "\\";
        }
        public Dictionary<string, List<string>> GetDeviceList()
        {
            Dictionary<string, List<string>> deviceList = new Dictionary<string, List<string>>();
            foreach (string key in Dics.Keys)
            {
               // TreeNode tn = new TreeNode(key);
                List<string> device = new List<string>();
                foreach (ConfigInfo d in Dics[key].Values)
                {
                    string  deviceName = d.GetValue("DeviceName");
                    device.Add(deviceName);

                }
                deviceList.Add(key, device);
                //device.Clear();

            }
            return deviceList;
        }

        public DeviceInfo GetDeviceInfo(string DeviceArea, string DeviceName)
        {
            string ip = Dics[DeviceArea][DeviceName].GetValue("DeviceIp");
            string port = Dics[DeviceArea][DeviceName].GetValue("DevicePort");
            string user = Dics[DeviceArea][DeviceName].GetValue("DeviceUser");
            string pass = Dics[DeviceArea][DeviceName].GetValue("DevicePass");
            string address = Dics[DeviceArea][DeviceName].GetValue("DeviceAddress");
            return new DeviceInfo(ip, port, user, pass, byte.Parse(address));
        }
      
    }
}
